import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/data/model/response/address_model.dart';
import 'package:efood_multivendor/data/model/response/response_model.dart';
import 'package:efood_multivendor/helper/location_permission.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/images.dart';

import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_loader.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/base/no_data_screen.dart';
import 'package:efood_multivendor/view/screens/address/widget/address_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';

class AccessLocationScreen extends StatefulWidget {
  final bool fromSignUp;
  final bool fromHome;
  final String route;
  AccessLocationScreen(
      {required this.fromSignUp, required this.fromHome, required this.route});

  @override
  State<AccessLocationScreen> createState() => _AccessLocationScreenState();
}

class _AccessLocationScreenState extends State<AccessLocationScreen> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bool _isLoggedIn = Get.find<AuthController>().isLoggedIn();
    if (_isLoggedIn) {
      Get.find<LocationController>().getAddressList();
    }

    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(children: [
        Image.asset(
          Images.setLocation,
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          fit: BoxFit.cover,
        ),
        SafeArea(
            child: Padding(
          padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
          child: GetBuilder<LocationController>(builder: (locationController) {
            return GetBuilder<LocationController>(
                builder: (locationController) {
              return Padding(
                padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(
                      height: 9.h,
                    ),
                    FittedBox(
                      child: Text(
                        'find_restaurants_and_foods'.tr,
                        textAlign: TextAlign.center,
                        style: sfMedium.copyWith(
                            fontWeight: FontWeight.bold,
                            fontSize: Dimensions.fontSizeExtraLarge * 1.8),
                      ),
                    ),
                    SizedBox(
                      width: MediaQuery.of(context).size.width / 1.3,
                      child: Text(
                        'by_allowing_location_access'.tr,
                        textAlign: TextAlign.justify,
                        style: sfRegular.copyWith(
                            fontSize: Dimensions.fontSizeSmall * 1.3,
                            color: Theme.of(context).disabledColor),
                      ),
                    ),
                    SizedBox(
                      height: Dimensions.PADDING_SIZE_SMALL,
                    ),
                    Get.find<SplashController>()
                                .configModel
                                ?.deadzoneAvailableOrder ==
                            1
                        ? SizedBox()
                        : Column(
                            children: [
                              Container(
                                  height:
                                      Dimensions.PADDING_SIZE_EXTRA_LARGE * 2.3,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(5),
                                    color: Color(0xffCECDD2).withOpacity(0.25),
                                    boxShadow: [
                                      BoxShadow(
                                        color:
                                            Color(0xff5A6CEA).withOpacity(0.07),
                                        offset: Offset(12, 26),
                                        blurRadius: 50,
                                        spreadRadius: 0,
                                      )
                                    ],
                                  ),
                                  width:
                                      MediaQuery.of(context).size.width / 1.1,
                                  child: Hero(
                                    tag: "SearchLocation",
                                    child: Center(
                                      child: TextFormField(
                                        onTap: () => Get.toNamed(
                                            RouteHelper.getPickMapRoute(
                                          widget.route.isEmpty
                                              ? widget.fromSignUp
                                                  ? RouteHelper.signUp
                                                  : RouteHelper.accessLocation
                                              : widget.route,
                                          widget.route.isEmpty,
                                        )),
                                        decoration: InputDecoration(
                                          prefixIcon: Icon(
                                            FeatherIcons.search,
                                            color: Colors.black,
                                          ),
                                          hintText: 'search_address_here'.tr,
                                          hintStyle: sfRegular.copyWith(
                                              fontSize:
                                                  Dimensions.fontSizeSmall *
                                                      1.5),
                                          border: InputBorder.none,
                                        ),
                                        onChanged: (value) {},
                                      ),
                                    ),
                                  )),
                              SizedBox(
                                height: Dimensions.PADDING_SIZE_SMALL * 1.8,
                              ),
                              Divider(
                                thickness: 1,
                                color: Color(0xff707070).withOpacity(0.1),
                              ),
                            ],
                          ),
                    ListTile(
                      onTap: () async {
                        LocationPermissionHelper.checkPermission(() async {
                          Get.dialog(CustomLoader(), barrierDismissible: false);
                          AddressModel? _address =
                              await Get.find<LocationController>()
                                  .getCurrentLocation(true);
                          ResponseModel? _response =
                              await locationController.getZone(
                                  _address!.latitude!,
                                  _address.longitude!,
                                  false);
                          if (_response?.isSuccess == true) {
                            Get.find<LocationController>()
                                .updateServiceAble(true);
                            locationController.saveAddressAndNavigate(
                                _address,
                                widget.fromSignUp,
                                widget.route,
                                widget.route.isNotEmpty);
                          } else {
                            Get.find<LocationController>()
                                .updateServiceAble(false);
                            if (Get.find<SplashController>()
                                    .configModel
                                    ?.deadzoneAvailableOrder ==
                                1) {
                              // Get.to(ServiceUnavailableScreen());
                            } else {
                              Get.back();
                              Get.toNamed(RouteHelper.getPickMapRoute(
                                  widget.route.isEmpty
                                      ? RouteHelper.accessLocation
                                      : widget.route,
                                  widget.route.isNotEmpty));
                              showCustomSnackBar(
                                  'service_not_available_in_current_location'
                                      .tr);
                            }
                          }
                        });
                      },
                      leading: SvgPicture.asset(Images.location_gps,
                          color: Theme.of(context).colorScheme.secondary),
                      title: Text(
                        "user_current_location".tr,
                        style: sfRegular.copyWith(
                            fontWeight: FontWeight.w600,
                            fontSize: Dimensions.fontSizeSmall * 1.6),
                      ),
                      subtitle: Text(
                        locationController.address,
                        style: sfRegular.copyWith(
                            fontSize: Dimensions.fontSizeSmall * 1.4),
                      ),
                    ),
                    Get.find<SplashController>()
                                .configModel
                                ?.deadzoneAvailableOrder ==
                            1
                        ? SizedBox()
                        : Column(
                            children: [
                              _isLoggedIn
                                  ? locationController.addressList.isNotEmpty
                                      ? locationController.addressList.length >
                                              0
                                          ? Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  'saved_address'.tr,
                                                  textAlign: TextAlign.center,
                                                  style: sfMedium.copyWith(
                                                      fontWeight:
                                                          FontWeight.bold,
                                                      fontSize: Dimensions
                                                              .fontSizeExtraLarge *
                                                          1.3),
                                                ),
                                                ListView.builder(
                                                  padding: EdgeInsets.all(
                                                      Dimensions
                                                          .PADDING_SIZE_SMALL),
                                                  physics:
                                                      BouncingScrollPhysics(),
                                                  itemCount: locationController
                                                      .addressList.length,
                                                  shrinkWrap: true,
                                                  itemBuilder:
                                                      (context, index) {
                                                    return Center(
                                                        child: SizedBox(
                                                            width: 700,
                                                            child:
                                                                AddressWidget(
                                                              fromSetting:
                                                                  false,
                                                              address:
                                                                  locationController
                                                                          .addressList[
                                                                      index],
                                                              fromAddress:
                                                                  false,
                                                              onTap: () {
                                                                Get.dialog(
                                                                    CustomLoader(),
                                                                    barrierDismissible:
                                                                        false);
                                                                AddressModel
                                                                    _address =
                                                                    locationController
                                                                            .addressList[
                                                                        index];
                                                                locationController.saveAddressAndNavigate(
                                                                    _address,
                                                                    widget
                                                                        .fromSignUp,
                                                                    widget
                                                                        .route,
                                                                    widget.route
                                                                        .isNotEmpty);
                                                              },
                                                            )));
                                                  },
                                                )
                                              ],
                                            )
                                          : NoDataScreen(
                                              text: 'no_saved_address_found'.tr)
                                      : !_isLoggedIn
                                          ? Container()
                                          : Center(
                                              child: CircularProgressIndicator
                                                  .adaptive(
                                              valueColor:
                                                  AlwaysStoppedAnimation<Color>(
                                                      Color(0xffff2222)),
                                              backgroundColor:
                                                  Color(0xffff8022),
                                            ))
                                  : SizedBox(),
                            ],
                          ),
                    SizedBox(height: Dimensions.PADDING_SIZE_LARGE),
                  ],
                ),
              );
            });
          }),
        )),
      ]),
    );
  }
}

class BottomButton extends StatelessWidget {
  final LocationController locationController;
  final bool fromSignUp;
  final String route;
  BottomButton(
      {required this.locationController,
      required this.fromSignUp,
      required this.route});

  @override
  Widget build(BuildContext context) {
    return Center(
        child: SizedBox(
            width: 700,
            child: Column(children: [
              CustomButton(
                buttonText: 'user_current_location'.tr,
                onPressed: () async {
                  LocationPermissionHelper.checkPermission(() async {
                    Get.dialog(CustomLoader(), barrierDismissible: false);
                    AddressModel? _address =
                        await Get.find<LocationController>()
                            .getCurrentLocation(true);
                    ResponseModel? _response = await locationController.getZone(
                        _address!.latitude!, _address.longitude!, false);
                    if (_response?.isSuccess == true) {
                      Get.find<LocationController>().updateServiceAble(true);
                      locationController.saveAddressAndNavigate(
                          _address, fromSignUp, route, route.isNotEmpty);
                    } else {
                      Get.find<LocationController>().updateServiceAble(false);
                      if (Get.find<SplashController>()
                              .configModel
                              ?.deadzoneAvailableOrder ==
                          1) {
                        // Get.to(ServiceUnavailableScreen());
                      } else {
                        Get.back();
                        Get.toNamed(RouteHelper.getPickMapRoute(
                            route.isEmpty ? RouteHelper.accessLocation : route,
                            route.isNotEmpty));
                        showCustomSnackBar(
                            'service_not_available_in_current_location'.tr);
                      }
                    }
                  });
                },
                icon: Icons.my_location,
              ),
              SizedBox(height: Dimensions.PADDING_SIZE_SMALL),
              TextButton(
                style: TextButton.styleFrom(
                  shape: RoundedRectangleBorder(
                    side: BorderSide(
                        width: 2, color: Theme.of(context).primaryColor),
                    borderRadius:
                        BorderRadius.circular(Dimensions.RADIUS_SMALL),
                  ),
                  minimumSize: Size(Dimensions.WEB_MAX_WIDTH, 50),
                  padding: EdgeInsets.zero,
                ),
                onPressed: () => Get.toNamed(RouteHelper.getPickMapRoute(
                  route.isEmpty
                      ? fromSignUp
                          ? RouteHelper.signUp
                          : RouteHelper.accessLocation
                      : route,
                  route.isNotEmpty,
                )),
                child:
                    Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                  Padding(
                    padding: EdgeInsets.only(
                        right: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                    child:
                        Icon(Icons.map, color: Theme.of(context).primaryColor),
                  ),
                  Text('set_from_map'.tr,
                      textAlign: TextAlign.center,
                      style: sfBold.copyWith(
                        color: Theme.of(context).primaryColor,
                        fontSize: Dimensions.fontSizeLarge,
                      )),
                ]),
              ),
            ])));
  }
}
